package com.life.wang.nio;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 数据------缓存------通道------文件
 */
public class writeFile {

    @Test   //向本地文件中写数据
    public void test1() throws Exception {
        //1 创建输出流
        FileOutputStream fos = new FileOutputStream("basic.txt");
        //2 从流中得到一个通道
        FileChannel fc = fos.getChannel();
        //3 提供一个缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //4 往缓冲区中存如数据
        String str = "hello,nio";
        buffer.put(str.getBytes());
        //5 翻转缓冲区
        buffer.flip();
        //6 把缓冲区写到通道中
        fc.write(buffer);
        //7 关闭
        fos.close();
    }

    @Test   //从本地文件中读取数据
    public void test2() throws Exception {
        //1 创建输入流
        File file = new File("basic.txt");
        FileInputStream fi = new FileInputStream(file);
        //2、从输入流中获取一个通道
        FileChannel fc = fi.getChannel();
        //3 提供一个缓冲区
        ByteBuffer buffer = ByteBuffer.allocate((int)file.length());
        //4 把通道数据写到缓冲区
        fc.read(buffer);
        System.out.println(new String(buffer.array()));
        //5 关闭
        fi.close();
    }

    @Test   //使用nio实现文件复制
    public void test3() throws Exception {
        //1 创建两个流
        FileInputStream fi = new FileInputStream("basic.txt");
        FileOutputStream fo = new FileOutputStream("basic2.txt");
        //2 获取两个通道
        FileChannel sourceFC = fi.getChannel();
        FileChannel destFC = fo.getChannel();
        //3 复制
        destFC.transferFrom(sourceFC,0,sourceFC.size());
        //4 关闭
        fi.close();
        fo.close();
    }
}
